package com.gedmanager.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class LicenseDataSource {

  // Database fields
  private SQLiteDatabase database;
  private MySQLiteHelper dbHelper;
  private String[] allColumns = { MySQLiteHelper.LICENSE_ID,
      MySQLiteHelper.LICENSE_LIMIT, MySQLiteHelper.LICENSE_INSTALL };

  public LicenseDataSource(Context context) {
    dbHelper = new MySQLiteHelper(context);
  }

  public void open() throws SQLException {
    database = dbHelper.getWritableDatabase();
  }

  public void close() {
    dbHelper.close();
  }

  public License createLicense( long date, long install_date) {
    ContentValues values = new ContentValues();
  
    values.put(MySQLiteHelper.LICENSE_LIMIT, date);
    values.put(MySQLiteHelper.LICENSE_INSTALL, install_date);

    long insertId = database.insert(MySQLiteHelper.TABLE_LICENSE, null,
        values);
    Cursor cursor = database.query(MySQLiteHelper.TABLE_LICENSE,
        allColumns, MySQLiteHelper.LICENSE_ID + " = " + insertId, null,
        null, null, null);
    cursor.moveToFirst();
    License newLicense = cursorToLicense(cursor);
    cursor.close();
    return newLicense;
  }

  public void deleteLicense(long id) {    
    System.out.println("License deleted with id: " + id);
    database.delete(MySQLiteHelper.TABLE_LICENSE, MySQLiteHelper.LICENSE_ID
        + " = " + id, null);
  }

  public List<License> getAllLicenses() {
    List<License> licenses = new ArrayList<License>();

    Cursor cursor = database.query(MySQLiteHelper.TABLE_LICENSE,
        allColumns, null, null, null, null, MySQLiteHelper.LICENSE_LIMIT+" DESC");

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
    	License license = cursorToLicense(cursor);
    	licenses.add(license);
      cursor.moveToNext();
    }
    // make sure to close the cursor
    cursor.close();
    return licenses;
  }
  


  private License cursorToLicense(Cursor cursor) {
	  License license = new License();
	  license.setId(cursor.getLong(0));
	  license.setDate(cursor.getLong(1));
	  license.setInstallDate(cursor.getLong(2));

    
    return license;
  }
} 